package com.example.loginproject.view.fragments

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import com.example.loginproject.R
import com.example.loginproject.databinding.FragmentPinRegistoryBinding
import com.example.loginproject.tool.AnimTools
import com.example.loginproject.tool.navigateTo
import com.example.loginproject.view.viewModels.ButtonStata
import com.example.loginproject.view.viewModels.SharedViewModel
import com.example.loginproject.view.views.UserInputView


class PinRegisterFragment : Fragment() {
    private lateinit var binding: FragmentPinRegistoryBinding
    private val viewModel: SharedViewModel by activityViewModels()
    private lateinit var name:String
    private lateinit var password:String
    private lateinit var confimrPassword:String
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentPinRegistoryBinding.inflate(layoutInflater,container,false)
        // Inflate the layout for this fragment
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.registBtnIsEnable.observe(viewLifecycleOwner){
            binding.button.isEnabled = it
        }
        binding.nameInputView.textChangedListener={userInputView, text ->
            name = text//
            checkEnable() }
        binding.passwordInputView.textChangedListener={userInputView, text ->//
            password= text
            checkEnable() }
        binding.confimrPasswordInputView.textChangedListener={userInputView,text ->
            confimrPassword = text
            checkEnable() }
        binding.button.setOnClickListener {
            checkPassword()
        }
    }
    private fun checkEnable(){
        val state = if(name.isNotEmpty()&&password.isNotEmpty()&&confimrPassword.isNotEmpty()){
            ButtonStata.Enabled//
        }else{
            ButtonStata.UnEnabled
        }
        viewModel.changeRegistButtonStata(state)
    }
    private fun checkPassword(){
        if(password == confimrPassword){
            viewModel.user.name = name
            viewModel.user.pin = password
            navigateTo(PatternRegisterFragment(), addToStack = false)
        }else{
            binding.passwordInputView.showError()
            binding.confimrPasswordInputView.showError()
            AnimTools.startSwingAnim(binding.button)
        }
    }
}